package com.hjy.demo.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjy.demo.pojo.Role;
import com.hjy.demo.service.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService roleService;

    @RequestMapping("/list")
    public String userInfo(Model model, String roleName
            , @RequestParam(required = false,defaultValue = "1")Integer pageIndex)
    {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (roleName!=null){
            wrapper.like("role_name",roleName);
        }
        Page<Role> page = new Page<>(pageIndex,5);
        IPage<Role> pages=roleService.RolePage(page,wrapper);

        model.addAttribute("pages",pages);
        return "/role/list";

    }

    @GetMapping("/add")
    public String getadd(Model model){
        return "/role/add";
    }

    @RequestMapping("/save")
    public String add(Model model, Role role){
        if (role!=null){
            if(roleService.addRole(role)>0){
                return "redirect:/role/list";
            }
        }
        return "/role/add";
    }

    @GetMapping("/edit")
    public String edit(Model model, Long roleId){
        Role role=roleService.getRole(roleId);
        model.addAttribute("role",role);
        return "/role/edit";
    }

    @RequestMapping("/updateSave")
    public String edit(Model model, Role role){
        if (role!=null){
            if(roleService.updateRole(role)>0){
                return "redirect:/role/list";
            }
        }
        return "redirect:/role/edit?roleId="+role.getRoleId();
    }

    @GetMapping("/del")
    @ResponseBody
    public Object del(Long roleId){
        return roleService.deleteRole(roleId)>0;
    }

}
